using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using Aspose.Words;
using Aspose.Words.Saving;
using Path = System.IO.Path;

namespace myconsole3;

public class ConverterWord
{
    public static void ToPdf(string sourcePath, string targetPath)
    {
        SetLicense();
        Document doc = new Document(sourcePath);
        doc.Save(targetPath, SaveFormat.Pdf);
    }

    /// <summary>
    /// 转换为图片
    /// </summary>
    /// <param name="sourcePath">原路径</param>
    /// <param name="targetPath">目标文件夹</param>
    /// <param name="startPageNum">开始页面</param>
    /// <param name="endPageNum">结束页面</param>
    /// <param name="imageFormat">格式</param>
    /// <param name="resolution">清晰度</param>
    /// <returns></returns>
    public static List<string> ToImage(
        string sourcePath,
        string targetPath,
        int startPageNum = 1,
        int endPageNum = int.MaxValue,
        ImageFormat imageFormat = null,
        int resolution = 128
    )
    {
        SetLicense();
        string pdfPath = Path.ChangeExtension(sourcePath, "temp");
        ToPdf(sourcePath, pdfPath);
        var imgList = ConverterPdf.ToImage(
            pdfPath,
            targetPath,
            startPageNum,
            endPageNum,
            imageFormat,
            resolution
        );
        if (File.Exists(pdfPath))
        {
            File.Delete(pdfPath);
        }

        return imgList;
    }

    /// <summary>
    /// 转换为图片的方法
    /// 你可以像这样调用该方法： ToImage("F:\\PdfFile.doc", "F:\\ImageFile", 1, 20, ImageFormat.Png, 256);
    /// </summary>
    /// <param name="sourcePath"></param>
    /// <param name="targetPath">
    /// 图片输出路径，如果为空，默认值为Word所在路径
    /// </param>
    /// <param name="startPageNum">
    /// 从PDF文档的第几页开始转换，如果为0，默认值为1
    /// </param>
    /// <param name="endPageNum">
    /// 从PDF文档的第几页开始停止转换，如果为0，默认值为Word总页数
    /// </param>
    /// <param name="imageFormat">
    /// 设置所需图片格式，如果为null，默认格式为JPEG
    /// </param>
    /// <param name="resolution">
    /// 设置图片的像素，数字越大越清晰，如果为0，默认值为128，建议最大值不要超过1024
    /// </param>
    public static List<string> ToImage2(
        string sourcePath,
        string targetPath,
        int startPageNum = 1,
        int endPageNum = int.MaxValue,
        ImageFormat imageFormat = null,
        float resolution = 256
    )
    {
        SetLicense();
        string imageName = Path.GetFileNameWithoutExtension(sourcePath).Replace(" ", "");

        // 返回的图片绝对路径集合
        List<string> images = new List<string>();
        try
        {
            // open word file
            Document doc = new Document(sourcePath);

            if (targetPath.Trim().Length == 0)
            {
                targetPath = Path.GetDirectoryName(sourcePath);
            }

            if (!Directory.Exists(targetPath))
            {
                if (targetPath != null)
                {
                    Directory.CreateDirectory(targetPath);
                }
            }

            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }

            if (endPageNum > doc.PageCount || endPageNum <= 0)
            {
                endPageNum = doc.PageCount;
            }

            if (startPageNum > endPageNum)
            {
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }

            if (imageFormat == null)
            {
                imageFormat = ImageFormat.Jpeg;
            }

            if (resolution <= 0)
            {
                resolution = 128;
            }

            ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat))
            {
                Resolution = resolution
            };

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                imageSaveOptions.PageIndex = i - 1;
                if (targetPath != null)
                {
                    string pathAll = Path.Combine(
                        targetPath,
                        imageName + "_" + i + "." + imageFormat.ToString().ToLower()
                    );
                    doc.Save(pathAll, imageSaveOptions);
                    images.Add(pathAll);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(
                "The document appears to be corrupted and cannot be loaded.".Equals(ex.Message)
                    ? "文件似乎已损坏，无法加载。"
                    : "文件被占用请关闭后重新导入"
            );
        }

        return images;
    }

    private static void SetLicense()
    {
        new License().SetLicense(
            new MemoryStream(
                Convert.FromBase64String(
                    "PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5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dqYWtaL1E9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4="
                )
            )
        );
    }

    private static SaveFormat GetSaveFormat(ImageFormat imageFormat)
    {
        SaveFormat sf;
        if (imageFormat.Equals(ImageFormat.Png))
        {
            sf = SaveFormat.Png;
        }
        else if (imageFormat.Equals(ImageFormat.Jpeg))
        {
            sf = SaveFormat.Jpeg;
        }
        else if (imageFormat.Equals(ImageFormat.Tiff))
        {
            sf = SaveFormat.Tiff;
        }
        else if (imageFormat.Equals(ImageFormat.Bmp))
        {
            sf = SaveFormat.Bmp;
        }
        else
        {
            sf = SaveFormat.Unknown;
        }

        return sf;
    }
}
